package com.sike.netty.rumen.shizhan_rengong.server.handler;

import com.sike.netty.rumen.shizhan_rengong.common.ChannelSessionMemory;
import com.sike.netty.rumen.shizhan_rengong.common.MessageTypeEnum;
import com.sike.netty.rumen.shizhan_rengong.common.ServiceAnswerSet;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class AiAnswerHandler extends SimpleChannelInboundHandler {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        String[] messages = ((String) msg).split("&");
        String key = messages[0];

        Channel channel = ctx.channel();
        String userChannelId = channel.id().toString();

        if (MessageTypeEnum.USER_QUESTION.getType().equals(key)) {
            String value = messages[1];

            if ("0".equals(value)) {
                // 转交给人工 handler 处理
                String rgChannelId = ChannelSessionMemory.getRgChannelId();
                if (rgChannelId == null) {
                    // 如果没有，先将用户添加到等待队列，然后返回给用户目前暂无人工坐席
                    ChannelSessionMemory.putWaitingUser(userChannelId);
                    channel.writeAndFlush("当前暂无人工坐席，继续等待请输入 0 ，退出请输入 9");
                } else {
                    Channel rgChannel = ChannelSessionMemory.getClientChannel(rgChannelId);
                    rgChannel.writeAndFlush(MessageTypeEnum.USER_HELLO.getType() + "&" + userChannelId + "|有用户咨询");
                }
            } else if ("9".equals(value)) {
                // 用户退出
                ChannelSessionMemory.deleteWaitingUser(userChannelId);
                channel.writeAndFlush("对不起，无法解决您的问题，深感抱歉");
            } else {
                String answer = ServiceAnswerSet.getAnswer(value);

                // 需要区分只能客服了
                answer = MessageTypeEnum.USER_QUESTION.getType() + "&" + answer;
                channel.writeAndFlush(answer);
            }
        } else {
            ctx.fireChannelRead(msg);
        }
    }
}
